package com.baor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baor.dao.OrderDao;
import com.baor.dao.OrderLogDao;
import com.baor.domain.OrderLogVo;
import com.baor.domain.OrderVo;
import com.baor.feign.DistributionFeign;
import com.baor.service.OrderService;
import com.baor.utils.AjaxResult;
import com.baor.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.baor.utils.DateUtil.now;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderLogDao orderLogDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DistributionFeign distributionFeign;

    @Override
    public AjaxResult<?> orderList(Map<String, Object> params) {
        params.put("pageIndex", (int)params.get("pageSize") * ((int)(params.get("pageIndex")) - 1));
        params.put("pageSize", params.get("pageSize"));
        Map<String,Object> res = new HashMap<>();
        res.put("orderList",orderDao.orderList(params));
        res.put("pageCount",orderDao.pageCount(params));
      return AjaxResult.success(res);
    }

    @Override
    public AjaxResult<?> orderInfo(Map<String, Object> params) {
        return AjaxResult.success(this.orderDao.orderInfo(params));
    }

    @Override
    public AjaxResult<?> orderRemark(Map<String, Object> params) {
        if(this.orderDao.orderRemark(params)>0){
            return AjaxResult.success(this.orderDao.orderRemark(params));
        }else {
            return AjaxResult.error("备注失败");
        }

    }

    @Override
    public AjaxResult<?> orderSourceList() {
        return AjaxResult.success(this.orderDao.orderSourceList());
    }

    @Override
    public AjaxResult<?> payMethodList() {
        return AjaxResult.success(this.orderDao.payMethodList());
    }

    @Override
    public AjaxResult<?> orderCodeList() {
        return AjaxResult.success(this.orderDao.orderCodeList());
    }

    @Override
    public AjaxResult<?> orderStatusList() {
        return AjaxResult.success(this.orderDao.orderStatusList());
    }

    @Override
    public AjaxResult<?> orderNotes(Map<String, Object> params) {
        return AjaxResult.success(this.orderDao.orderNotes(params));
    }

    @Override
    public AjaxResult<?> orderLogList(Map<String, Object> params) {
        return AjaxResult.success(this.orderDao.orderLogList(params));
    }

    @Override
    public AjaxResult<?> updateOrderStatus(Map<String, Object> params) {
        Map<String,Object> res = new HashMap<>();
        res.put("orderId",params.get("orderId"));
        res.put("orderStatusId",params.get("orderStatusId"));
        //判断是否可以成为分销商
        if(Integer.parseInt(res.get("orderStatusId").toString()) == 12){
            int userId = Integer.parseInt(orderDao.selectById((int) res.get("orderId")).getUserId());
            distributionFeign.people(userId);
        }
        if(this.orderDao.updateOrderStatus(res)>0){
            this.orderLogDao.insertOrderLog(params);
            distributionFeign.updateCommission((Integer) params.get("orderId"));
            return AjaxResult.success("更新成功");
        }else {
            return AjaxResult.error("更新失败");
        }
    }

    @Override
    public AjaxResult<?> addOrder(Map<String, Object> params) {
        params.put("id", 0);
        params.put("orderCode", generateOrderCode());
        if (this.orderDao.addOrder(params) > 0) {
            OrderVo orderVo = orderDao.selectById((int) params.get("id"));
            System.out.println(distributionFeign.insertProxyOrder(orderVo));
            return AjaxResult.success("新增成功");
        } else {
            return AjaxResult.error("新增失败");
        }
    }
    private String generateOrderCode() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 15; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    @Override
    public AjaxResult<?> createUpdateOrderStatusEvent(Map<String, Object> map) {
        int autoReceipt = (int) map.get("autoReceipt");
        String sql = "ALTER EVENT UpdateOrderStatusEventAfterDays "
                + "ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY "
                + "DO "
                + "BEGIN "
                + "DECLARE autoReceipt INT; "
                + "SET autoReceipt = ?; "
                + "UPDATE t_order "
                + "SET order_status_id = 20 "
                + "WHERE order_status_id != 20 AND TIMESTAMPDIFF(DAY, create_time, NOW()) >= autoReceipt; "
                + "END";
        jdbcTemplate.update(sql,autoReceipt);

        return AjaxResult.success("修改成功"); // 这里可以根据需要返回相应的结果
    }

    @Override
    public AjaxResult<?> minuteEvent(Map<String, Object> map) {
        int autoCancel = (int) map.get("autoCancel");
        System.out.println("执行定时任务，时间间隔：" + autoCancel + "秒钟");

        String sql = "ALTER EVENT UpdateOrderStatusEvent " +
                "ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 MINUTE " +
                "DO " +
                "BEGIN " +
                "DECLARE autoCancel INT; " +
                "SET autoCancel = " + autoCancel + "; " +
                "UPDATE t_order " +
                "SET order_status_id = 20 " +
                "WHERE order_status_id = 2 AND TIMESTAMPDIFF(SECOND, create_time, NOW()) >= autoCancel; " +
                "END";

        jdbcTemplate.update(sql);
        return AjaxResult.success("修改成功");
    }

    @Override
    public AjaxResult<?> addOrderSetting(Map<String, Object> params) {
        return AjaxResult.success(this.orderDao.addOrderSetting(params));
    }

    @Override
    public AjaxResult<?> orderSettingList(Map<String, Object> params) {
        return AjaxResult.success(this.orderDao.orderSettingList(params));
    }

    @Override
    public AjaxResult<?> UpdateOrderBackEvent(Map<String, Object> params) {
        int backDay = (int) params.get("backDay");
        String sql = "ALTER EVENT UpdateOrderBackEvent "
                + "ON SCHEDULE EVERY 1 DAY "
                + "DO "
                + "BEGIN "
                + "UPDATE t_order "
                + "SET order_back = 1 "
                + "WHERE sign_time <= DATE_SUB(NOW(), INTERVAL ? DAY); "
                + "END";
        jdbcTemplate.update(sql, backDay);
        return AjaxResult.success("已修改UpdateOrderStatusEvent事件，每天执行一次，更新超过" + backDay + "天的订单状态为不可退货");
    }

    @Override
    public AjaxResult<?> updateOrderToLog(OrderVo vo) {
        String userId = vo.getUserId();
        vo.setUserId(null);
        orderDao.update(vo,new LambdaQueryWrapper<OrderVo>()
                .eq(OrderVo::getSiteId,vo.getSiteId())
                .eq(OrderVo::getOrderId,vo.getOrderId()));
        OrderLogVo orderLogVo = new OrderLogVo();
        orderLogVo.setOrderId(vo.getOrderId().toString());
        orderLogVo.setOrderStatusId(vo.getOrderStatusId());
        orderLogVo.setCreateTime(DateUtil.now());
        orderLogVo.setSiteId(vo.getSiteId());
        orderLogVo.setUserName(userId);
        orderLogDao.insert(orderLogVo);
        return AjaxResult.success(orderLogVo.getOrderLogId());
    }


}

